<?php
// Model
use App\Models\Region;
use App\Models\Order;
use App\Models\BetNumber;
use App\Models\WinningLotteryNumber;
use App\Models\WinningHistory;

// Function

// determine the prizes to winning numbers by region. | General Prizes, Grand Prizes, Consolation Prizes
if(!function_exists("determinePrizesToWinningNumbers")) {
	function determinePrizesToWinningNumbers($region, $date) {
        // check determinability of prizes=====
        $todayWinningNumber = WinningLotteryNumber::where('region_id', $region->id)
                                                    ->where('date', $date)
                                                    ->where('is_determined', true)
                                                    ->where('checked_winning', false)

         //====                                           ->first();
	if (!$todayWinningNumber) {
            return false;
        }
        // winning numbers=====
        $rank1_number = $todayWinningNumber->rank1_number;
        $rank2_number = $todayWinningNumber->rank2_number;
        $rank3_number = $todayWinningNumber->rank3_number;
        // General Prizes====
        determineGeneralPrizesToWinningNumbers($region, $date, $rank1_number, 1); // $region: object, $rank_number: number, $rank: number
        determineGeneralPrizesToWinningNumbers($region, $date, $rank2_number, 2);
        determineGeneralPrizesToWinningNumbers($region, $date, $rank3_number, 3);
        // Grand Prizes
        determineGrandPrizesToWinningNumbers($region, $date, $rank1_number);
        // Consolation Prizes
        if($region->id == 1) {
//            determineConsolationPrizesToWinningNumbers($region, $date, $rank1_number, 1); // for only 4 digits
//            determineConsolationPrizesToWinningNumbers($region, $date, $rank2_number, 2);
//            determineConsolationPrizesToWinningNumbers($region, $date, $rank3_number, 3);
        }
        //
//        $todayWinningNumber->checked_winning = true;
        $todayWinningNumber->save();
    }
}

// ================================================================ //
// ============= General Prizes To Winning Numbers ================ //
// ================================================================ //
// determine the general prizes to winning umbers by region | General Prizes
if(!function_exists("determineGeneralPrizesToWinningNumbers")) {
    function determineGeneralPrizesToWinningNumbers($region, $date, $rank_number, $rank) {
        $tomorrow = date('Y-m-d', strtotime($date) + 86400);
        // 4digits
        $betNumbers4 = BetNumber::whereHas('order', function ($query) use ($region) {
                                    $query->where('is_deleted', false)
                                        ->where('belong_to', 'LIKE', '%' . "$region->region_key" . '%');
                                })
                                ->with('order')
                                ->where('is_pool', false)
                                ->where('bet_number', $rank_number)
                                ->where('created_at', '>=', $date . ' 04:00:00')
                                ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                                ->get();
	//
        determineGeneralPrizesToWinningNumbersByDigit($betNumbers4, $region, $rank, 4);
        // 3digits
        $betNumbers3 = BetNumber::whereHas('order', function ($query) use ($region) {
                                    $query->where('is_deleted', false)
                                        ->where('belong_to', 'LIKE', '%' . "$region->region_key" . '%');
                                })
                                ->with('order')
                                ->where('is_pool', false)
                                ->where('bet_number', substr($rank_number, -3))
                                ->where('created_at', '>=', $date . ' 04:00:00')
                                ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                                ->get();
        //
        determineGeneralPrizesToWinningNumbersByDigit($betNumbers3, $region, $rank, 3);
        // 2digits
        $betNumbers2 = BetNumber::whereHas('order', function ($query) use ($region) {
                                    $query->where('is_deleted', false)
                                        ->where('belong_to', 'LIKE', '%' . "$region->region_key" . '%');
                                })
                                ->with('order')
                                ->where('is_pool', false)
                                ->where('bet_number', substr($rank_number, -2))
                                ->where('created_at', '>=', $date . ' 04:00:00')
                                ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                                ->get();
        //
        determineGeneralPrizesToWinningNumbersByDigit($betNumbers2, $region, $rank, 2);
    }
}

if(!function_exists("determineGeneralPrizesToWinningNumbersByDigit")) {
    function determineGeneralPrizesToWinningNumbersByDigit($betNumbers, $region, $rank, $digit) {
	  foreach ($betNumbers as $betNumber) {
            $betNum = BetNumber::find($betNumber->id);
            $betNum->is_winner = true;
            $betNum->rank = $rank;
	    $betNum->prizes = $betNum->prizes + getGeneralPrizes($betNumber->bet_number, $rank, $betNum->bet_money);
            $betNum->winning_payment_time = date('Y-m-d H:i:s');
            $betNum->save();
            // update total winning amount for order
            $order = Order::find($betNum->order_id);
            $order->total_winning_amount = $order->total_winning_amount + getGeneralPrizes($betNumber->bet_number, $rank, $betNum->bet_money);
            $order->is_winner = true;
            $order->save();
            // save winning history
            WinningHistory::updateOrCreate(
                [
                    'bet_number_id' => $betNum->id,
                    'bet_number' => $betNum->bet_number,
                    'machine_number' => $order->machine_number,
                    'serial_number' => $order->serial_number,
                    'order_id' => $betNum->order_id,
                    'region_id' => $region->id,
                    'rank' => $rank,
                    'digit' => $digit,
                    'created_at' => $betNum->created_at,
                ],
                [
                    'prizes_type' => 'general',
                    'prizes' => getGeneralPrizes($betNumber->bet_number, $rank, $betNum->bet_money)
                ]
            );
        }
    }
}

if(!function_exists("getGeneralPrizes")) {//========
    function getGeneralPrizes($bet_number, $rank, $bet_money) {
        $amount = 0;
        // default winning amount arr
        $digit4num = [3000, 1500, 750];
        $digit3num = [400, 200, 100];
        $digit2num = [40, 20, 10];
        // calc amount by digits, rank
        switch(strlen($bet_number)) {
            case 4 : $amount = $digit4num[$rank - 1]; break;
            case 3 : $amount = $digit3num[$rank - 1]; break;
            case 2 : $amount = $digit2num[$rank - 1]; break;
            default : $amount = 0; break;
        }

        return $amount * $bet_money;
    }
}

// ============================================================== //
// ============= Grand Prizes To Winning Numbers ================ //
// ============================================================== //
//
if(!function_exists("determineGrandPrizesToWinningNumbers")) {//=================
    function determineGrandPrizesToWinningNumbers($region, $date, $rank_number) {
        $tomorrow = date('Y-m-d', strtotime($date) + 86400);
        // 4digits
        $betNumbers4 = BetNumber::whereHas('order', function ($query) use ($region) {
                                $query->where('is_deleted', false)
                                    ->where('belong_to', 'LIKE', '%' . "$region->region_key" . '%');
                            })
                            ->with('order')
                            ->where('is_pool', true)
                            ->where('bet_number', $rank_number . ' P')
                            ->where('created_at', '>=', $date . ' 04:00:00')
                            ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                            ->get();
        //
        determineGrandPrizesToWinningNumbersByDigit($betNumbers4, $region, 4);
        // 3digits
        $betNumbers3 = BetNumber::whereHas('order', function ($query) use ($region) {
                                $query->where('is_deleted', false)
                                    ->where('belong_to', 'LIKE', '%' . "$region->region_key" . '%');
                            })
                            ->with('order')
                            ->where('is_pool', true)
                            ->where('bet_number', substr($rank_number, -3) . ' P')
                            ->where('created_at', '>=', $date . ' 04:00:00')
                            ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                            ->get();
        //
        determineGrandPrizesToWinningNumbersByDigit($betNumbers3, $region, 3);
        // 2digits
        $betNumbers2 = BetNumber::whereHas('order', function ($query) use ($region) {
                                $query->where('is_deleted', false)
                                    ->where('belong_to', 'LIKE', '%' . "$region->region_key" . '%');
                            })
                            ->with('order')
                            ->where('is_pool', true)
                            ->where('bet_number', substr($rank_number, -2) . ' P')
                            ->where('created_at', '>=', $date . ' 04:00:00')
                            ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                            ->get();
        //
        determineGrandPrizesToWinningNumbersByDigit($betNumbers2, $region, 2);
    }
}

if(!function_exists("determineGrandPrizesToWinningNumbersByDigit")) {//=========
    function determineGrandPrizesToWinningNumbersByDigit($betNumbers, $region, $digit) {
        foreach ($betNumbers as $betNumber) {
            $betNum = BetNumber::find($betNumber->id);
            $betNum->is_winner = true;
            $betNum->rank = 1;
            $betNum->prizes = $betNum->prizes + getGrandPrizes($digit, $betNum->bet_money);
            $betNum->winning_payment_time = date('Y-m-d H:i:s');
            $betNum->save();
            // update total winning amount for order
            $order = Order::find($betNum->order_id);
            $order->total_winning_amount = $order->total_winning_amount + getGrandPrizes($digit, $betNum->bet_money);
            $order->is_winner = true;
            $order->save();
            // save winning history
            WinningHistory::updateOrCreate(
                [
                    'bet_number_id' => $betNum->id,
                    'bet_number' => $betNum->bet_number,
                    'machine_number' => $order->machine_number,
                    'serial_number' => $order->serial_number,
                    'order_id' => $betNum->order_id,
                    'region_id' => $region->id,
                    'rank' => 1,
                    'digit' => $digit,
                    'created_at' => $betNum->created_at,
                ],
                [
                    'prizes_type' => 'grand',
                    'prizes' => getGrandPrizes($digit, $betNum->bet_money)
                ]
            );
        }
    }
}

if(!function_exists("getGrandPrizes")) {
    function getGrandPrizes($digit, $bet_money) {
        $amount = 0;
        // default winning amount arr
        $digit4num = [3000, 1500, 750];
        $digit3num = [400, 200, 100];
        $digit2num = [40, 20, 10];
        // calc amount by digits, rank
        switch($digit) {
            case 4 : $amount = $digit4num[0] + $digit4num[1] + $digit4num[2]; break;
            case 3 : $amount = $digit3num[0] + $digit3num[1] + $digit3num[2]; break;
            case 2 : $amount = $digit2num[0] + $digit2num[1] + $digit2num[2]; break;
            default : $amount = 0; break;
        }

        return $amount * $bet_money;
    }
}

// ============================================================== //
// ============ Consolation Prizes To Winning Numbers =========== //
// ============================================================== //
//
// if(!function_exists("determineConsolationPrizesToWinningNumbers")) {
//     function determineConsolationPrizesToWinningNumbers($region, $date, $rank_number, $rank) {
//         $tomorrow = date('Y-m-d', strtotime($date) + 86400);
//         // -1 consolation rank number
//         $rank_number_A = ((int)$rank_number) - 1;
//         if(strlen($rank_number_A) == 4) {
//             $betNumbersA = BetNumber::whereHas('order', function ($query) use ($region) {
//                             $query->where('is_deleted', false)
//                                 ->where('belong_to', 'LIKE', '%' . $region->region_key . '%');
// //                                ->where('is_winner', false);
//                         })
//                         ->with('order')
//                         ->where('is_pool', false)
// //                        ->where('is_winner', false)
//                         ->where('bet_number', $rank_number_A)
//                         ->where('created_at', '>=', $date . ' 04:00:00')
//                         ->where('created_at', '<=', $tomorrow . ' 03:59:59')
//                         ->get();
//             //
//             determineConsolationPrizesToWinningNumbersFunc($betNumbersA, $region, $rank);
//         }
//         // +1 consolation rank number
//         $rank_number_B = ((int)$rank_number) + 1;
//         if(strlen($rank_number_B) == 4) {
//             $betNumbersB = BetNumber::whereHas('order', function ($query) use ($region) {
//                             $query->where('is_deleted', false)
//                                 ->where('belong_to', 'LIKE', '%' . $region->region_key . '%');
// //                                ->where('is_winner', false);
//                         })
//                         ->with('order')
//                         ->where('is_pool', false)
// //                        ->where('is_winner', false)
//                         ->where('bet_number', $rank_number_B)
//                         ->where('created_at', '>=', $date . ' 04:00:00')
//                         ->where('created_at', '<=', $tomorrow . ' 03:59:59')
//                         ->get();
//             //
//             determineConsolationPrizesToWinningNumbersFunc($betNumbersB, $region, $rank);
//         }
//     }
// }

// if(!function_exists("determineConsolationPrizesToWinningNumbersFunc")) {
//     function determineConsolationPrizesToWinningNumbersFunc($betNumbers, $region, $rank) {
//         foreach ($betNumbers as $betNumber) {
//             $betNum = BetNumber::find($betNumber->id);
//             $betNum->is_winner = true;
//             $betNum->rank = $rank;
//             $betNum->prizes = $betNum->prizes + getConsolationPrizes($betNumber->bet_money);
//             $betNum->winning_payment_time = date('Y-m-d H:i:s');
//             $betNum->save();
//             // update total winning amount for order
//             $order = Order::find($betNum->order_id);
//             $order->total_winning_amount = $order->total_winning_amount + getConsolationPrizes($betNumber->bet_money);
//             $order->is_winner = true;
//             $order->save();
//             // save winning history
//             WinningHistory::updateOrCreate(
//                 [
//                     'bet_number_id' => $betNum->id,
//                     'bet_number' => $betNum->bet_number,
//                     'machine_number' => $order->machine_number,
//                     'serial_number' => $order->serial_number,
//                     'order_id' => $betNum->order_id,
//                     'region_id' => $region->id,
//                     'rank' => $rank,
//                     'digit' => 4,
//                     'created_at' => $betNum->created_at,
//                 ],
//                 [
//                     'prizes_type' => 'consolation',
//                     'prizes' => getConsolationPrizes($betNumber->bet_money)
//                 ]
//             );
//         }
//     }
// }

// if(!function_exists("getConsolationPrizes")) {
//     function getConsolationPrizes($bet_money) {
//         $amount = 0;
//         if ($bet_money < 1) {
//             $amount = $bet_money * 100;
//         } else {
//             $amount = 100;
//         }
//
//         return $amount;
//     }
// }


// ============================================================ //
// ============================================================ //
// ============================================================ //
if(!function_exists("getPrizesFromWinningHistory")) {
    function getPrizesFromWinningHistory($machine_number, $serial_number, $bet_number, $region_id, $prizes_type, $rank, $digit, $start, $end) {
        $query = WinningHistory::where('region_id', $region_id)
                            ->where('prizes_type', $prizes_type);
        if($machine_number) {
            $query->where('machine_number', $machine_number);
        }
        if($serial_number) {
            $query->where('serial_number', $serial_number);
        }
        if($bet_number) {
            $query->where('bet_number', $bet_number);
        }
        if($prizes_type != 'consolation') {
            $query->where('rank', $rank);
        }
        $start = $start . ' 04:00:00';
        $end = date('Y-m-d H:i:s',strtotime('+4 hours',  strtotime($end . ' 23:59:59')));
        $query->where('digit', $digit)
            ->whereBetween('created_at', [$start, $end])
             ->where('created_at', '>=', $start)
             ->where('created_at', '<=', $end)
            ->orderBy('created_at', 'ASC');

        return $query->sum('prizes');
    }
}

if(!function_exists("getTotalPrizesFromWinningHistory")) {
    function getTotalPrizesFromWinningHistory($machine_number, $serial_number, $bet_number, $region_id, $start, $end) {
        $query = WinningHistory::where('region_id', $region_id);
        if($machine_number) {
            $query->where('machine_number', $machine_number);
        }
        if($serial_number) {
            $query->where('serial_number', $serial_number);
        }
        if($bet_number) {
            $query->where('bet_number', $bet_number);
        }
        $start = $start . ' 04:00:00';
        $end = date('Y-m-d H:i:s',strtotime('+4 hours',  strtotime($end . ' 23:59:59')));
         $query->where('created_at', '>=', $start)
             ->where('created_at', '<=', $end)
             ->orderBy('created_at', 'ASC');
            // var_dump($start, $end);exit;
        return $query->sum('prizes');
    }
}

if(!function_exists("getPrizesByBetNumber")) {
    function getPrizesByBetNumber($region_id, $prizes_type, $rank, $digit, $bet_number_id) {
        $query = WinningHistory::where('region_id', $region_id)
                            ->where('prizes_type', $prizes_type);
        if($prizes_type != 'consolation') {
            $query->where('rank', $rank);
        }
        $query->where('digit', $digit)
            ->where('bet_number_id', $bet_number_id)
            ->orderBy('created_at', 'ASC');

        return $query->sum('prizes');
    }
}

if(!function_exists("getTotalPrizesByBetNumber")) {
    function getTotalPrizesByBetNumber($region_id, $bet_number_id) {
        $query = WinningHistory::where('region_id', $region_id)
                            ->where('bet_number_id', $bet_number_id)
                            ->orderBy('created_at', 'ASC');

        return $query->sum('prizes');
    }
}
